package com.blyat.xsoft.gateway.ribbon.filter.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;

import java.util.Arrays;
import java.util.List;

/**
 * @Auther: syh
 * @Date: 2020/8/24
 * @Description: 如果过滤器规则很多，那么类文件就很多
 *  1 json文件的filter中添加如下代码：
 *       {
 *         "name": "IPForbid",
 *         "args": {
 *           "forbidIp": "0:0:0:0:0:0:0:1"
 *         }
 *       }
 *
 *  2 properties中
 *      spring.cloud.gateway.routes[0].filters[1].name=IPForbid
 *      spring.cloud.gateway.routes[0].filters[1].args.forbidIp=0:0:0:0:0:0:0:1
 */
public class IPForbidGatewayFilterFactory
        extends AbstractGatewayFilterFactory<IPForbidGatewayFilterFactory.Config> {
    private static final Logger logger = LoggerFactory.getLogger(IPForbidGatewayFilterFactory.class);

    public IPForbidGatewayFilterFactory() {
        super(Config.class);
    }

    /**
     * 指定config属性名称
     *
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("forbidIp");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
            logger.info("request url: {}", exchange.getRequest().getURI().getPath());
            logger.info("request ip: {}", ip);
            if (config.getForbidIp().equals(ip)) {
                return chain.filter(exchange);
            }
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();

        };
    }

    static public class Config {
        private String forbidIp;

        public String getForbidIp() {
            return forbidIp;
        }

        public void setForbidIp(String forbidIp) {
            this.forbidIp = forbidIp;
        }
    }
}
